package com.wynn.service.impl;

import com.wynn.dao.ProcedureDao;
import com.wynn.pojo.ManHour;
import com.wynn.service.ProcedureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@Transactional
@RequestMapping("procedure")
public class ProcedureServiceImpl implements ProcedureService {

    @Autowired
    private ProcedureDao procedureDao;

    @Override
    @GetMapping("selectAll")
    public List<ManHour> selectAll(){
        //代表工序
        int i = 1;
        //代表每个工序得所有产品工时
        List<ManHour> man_hours;
        //将相同工序不同产品的工时整理成一行
        List<ManHour> manHourSummary = new ArrayList<>();
        while(true){
            //按工序顺序查找工序
            man_hours =  procedureDao.findHourById(i);
            if (man_hours.size()==0){
                break;
            }
            //将查找出的工时整理为一行
            HashMap<String, Float> signalManHour = new HashMap<>();
            //每个产品对应的工时
            for (ManHour man_hour : man_hours) {
                signalManHour.put(man_hour.getProduct(),man_hour.getTiming());
            }

            ManHour row = man_hours.get(0);
            row.setTimingSummary(signalManHour);
            manHourSummary.add(row);
            i++;

        }
        return manHourSummary;

    }

    @Override
    @PostMapping("importHour")
    public void improtHour(@RequestBody List<List<String>> hourTable) {

        procedureDao.deleteAll();

        List<String> header = hourTable.get(0);
        //逐行添加
        List<String> row;
        for (int i = 1; i < hourTable.size() ; i++) {
            row = hourTable.get(i);
            for (int j = 2; j < header.size(); j++) {
                //第0列为顺序，第1列为工序名，第2列为产品名，第三列为时间
                procedureDao.addHour(row.get(0),row.get(1),header.get(j),row.get(j));
            }
        }
    }

    @Override
    @GetMapping("search")
    public List<ManHour> search(String name) {
        List<ManHour> manHours = procedureDao.searchByName(name);

        //将查找出的工时整理为一行
        HashMap<String, Float> signalManHour = new HashMap<>();
        //每个产品对应的工时
        for (ManHour man_hour : manHours) {
            signalManHour.put(man_hour.getProduct(),man_hour.getTiming());
        }

        //len=0表示没有搜读到数据
        int len = manHours.size();
        if (len==0){
            return manHours;
        }
        //整理成一行数据
        manHours.get(0).setTimingSummary(signalManHour);
        //只保留到第一行数据
        for (int i = 1; i < len; i++) {
            manHours.remove(1);
        }

        return manHours;
    }

    @Override
    @GetMapping("findTT")
    public float findTT() {
        return procedureDao.findTT();
    }

    @Override
    public void updateTT(float tt) {
        procedureDao.updateTT(tt);
    }


}
